package org.example.java.ref;

import java.util.Arrays;
import java.util.WeakHashMap;

/**
 * Created by Juntao.Zhang on 2014/11/23.
 */
public class WeakHashMapTest {
  static class Key {
    String id;

    public Key(String id) {
      this.id = id;
    }

    public String toString() {
      return id;
    }

    public int hashCode() {
      return id.hashCode();
    }

    public boolean equals(Object r) {
      return (r instanceof Key)
          && id.equals(((Key) r).id);
    }

    public void finalize() {
      System.out.println("Finalizing Key " + id);
    }
  }

  static class Value {
    String id;

    public Value(String id) {
      this.id = id;
    }

    public String toString() {
      return id;
    }

    public void finalize() {
      System.out.println("Finalizing Value " + id);
    }

  }

  public static void main(String[] args) throws Exception {
    int size = 10;

    if (args.length > 0) {
      size = Integer.parseInt(args[0]);
    }

    Key[] keys = new Key[size];
    WeakHashMap<Key, Value> whm = new WeakHashMap<Key, Value>();

    for (int i = 0; i < size; i++) {
      Key k = new Key(Integer.toString(i));
      Value v = new Value(Integer.toString(i));
      if (i % 3 == 0) {
        keys[i] = k;
      }

      whm.put(k, v);
    }
    System.out.printf("before gc WeakHashMap are %s.%n", whm.toString());
    System.gc();
    Thread.sleep(1000);  //把处理器的时间让给垃圾回收器进行垃圾回收
    System.out.printf("keys are %s.%n", Arrays.toString(keys));
    System.out.printf("after gc WeakHashMap are %s.%n", whm.toString());
  }

}
